import serial

# 创建Serial对象，配置串口参数
ser = serial.Serial('/dev/ttyS5', 9600)

file = None

try:
    with open('ble_ip_data', 'w') as file:
        while True:
            # 读取串口缓冲区的数据
            data = ser.read(ser.in_waiting)

            # 打印收到的数据
            if data:
                print(data.decode())

                if data.startswith(b"##"):
                    ip_address = data[2:].decode()
                    print("IP地址:",ip_address)

                 #将数据写入文件,并覆盖之前的数据
                    with open('ble_ip_data','w') as file: 
                        file.write(ip_address)
                        file.flush()
                 #将ble_ip_data中的数据读取出并发送到串口
                    with open('ble_ip_data','r') as read_file:  
                        file_content = read_file.read().strip()
                        ser.write(file_content.encode())

                if data==b'**0101': 
                    with open('ble_ip_data','r') as read_file:
                        file_content = read_file.read().strip()
                        ser.write(file_content.encode())

                if data==b'**0102':
                    with open('/root/.master_station_ip','r') as file:
                        file_content = file.read().strip()
                        ser.write(file_content.encode())
                
                else:
                    print("无效数据")
 

except KeyboardInterrupt:
    # 捕获 Ctrl+C 异常，关闭串口和文件
    ser.close()
    file.close()
